<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>AngularJS&middot;Hello AngularJS</title>
    <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.2/css/bootstrap.css">
    <style>
        .demo{
            margin-bottom:10px;
        }
        .statusBar{
            display: inline-block;
            text-align: center;
            width: 60px;
            height:60px;
            line-height: 60px;
            border-radius: 30px;
            background:#999;
        }
    </style>
</head>
<body>

 <div class="container">
     <div class="row">
         <nav class="navbar navbar-default navbar-static-top">
             <div class="container-fluid">
                 <div class="navbar-header">
                     <a class="navbar-brand" href="../index.html">首页</a>
                 </div>
                 <ul class="nav navbar-nav">
                    <li class="active"><a href="javascript:void(0)">Link</a></li>
                    <li><a href="javascript:void(0)">Link2</a></li>
                 </ul>
             </div>
         </nav>
     </div>
     <h3>http://www.npr.org/音频播放示例,参考：http://blog.jobbole.com/50022/</h3>
     <div class="row demo" ng-app="VideoAPP">
          <div class="row" ng-controller="PlayerController">
              <p class="text-center">
                  <span class="statusBar" ng-show="!player.playing">
                      <i class="glyphicon glyphicon-play-circle"></i><br>
                      等待播放
                  </span>
                  <span class="statusBar"  ng-show="player.playing">
                      <i class="glyphicon glyphicon-pause"></i><br>
                      播放中...
                  </span>
              </p>
              <p>
                 播放状态:{{player.playing}},播放周期：{{player.currentDuration()}},播放进度：{{player.currentTime()}}
              </p>
              <div class="col-md-8">
                  <ul id="programs_list" class="list-group">
                      <li class="list-group-item" ng-repeat="program in programs">
                          <span npr-link ng-model="program" player="player"></span>
                      </li>
                  </ul>
              </div>
              <div class="col-md-4" ng-controller="RelatedController">
                  <h5>正在播放音乐相关信息：</h5>
                  <ul id="related">
                      <li ng-repeat="s in related"><a href="{{ s.link }}">{{ s.caption }}</a></li>
                  </ul>
              </div>
          </div>
     </div>
 </div>
</body>
</html>
<script src="http://cdn.bootcss.com/angular.js/1.3.8/angular.js" type="text/javascript"></script>
<script>
    var apiKey = 'MDIyODg2ODk4MDE0NTYxMzI5NjBhNmRlYg000',
        nprUrl = 'http://api.npr.org/query?id=61&fields=relatedLink,title,byline,text,audio,image,pullQuote,all&output=JSON';

    var app=angular.module("VideoAPP",[]);

    //播放组件封装类
    app.factory('audio', ['$document', function($document) {
        var audio = $document[0].createElement('audio');
        return audio;
    }]);

    //播放器封装类
    app.factory('player', ['audio','$rootScope', function(audio,$rootScope) {
        var player = {
            playing: false,
            current: null,
            ready: false,
            play: function(program) {
                 // 如果正在播放，则停止当前播放
                if (player.playing) player.stop();
                var url = program.audio[0].format.mp4.$text;
                //重新渲染播放数据
                player.current = program;
                audio.src = url;
                audio.play();
                //更改播放状态
                player.playing = true
            },
            stop: function() {
                if (player.playing) {
                    audio.pause();
                    //暂停播放
                    //清除播放状态
                    player.ready = player.playing = false;
                    player.current = null;
                }
            },
            currentTime: function() {
                return audio.currentTime;
            },
            currentDuration: function() {
                return parseInt(audio.duration);
            }
        };
        //播放组件添加事件，便于更新状态和UI
        audio.addEventListener('ended', function() {
            $rootScope.$apply(player.stop());
        });
        audio.addEventListener('timeupdate', function(evt) {
            $rootScope.$apply(function() {
                player.progress = player.currentTime();
                player.progress_percent = player.progress / player.currentDuration();
            });
        });
        audio.addEventListener('canplay', function(evt) {
            $rootScope.$apply(function() {
                player.ready = true;
            });
        });
        return player;
    }]);

    //服务类作为发送http请求的封装类
    app.factory('nprService', ['$http', function($http) {
        var doRequest = function(successCallback,errorCallback) {
            return  $http({
                method: 'JSONP',
                url: nprUrl + '&apiKey=' + apiKey + '&callback=JSON_CALLBACK'
            }).success(successCallback).error(errorCallback);
        }
        return {
            getPrograms: function(success,error) { return doRequest(success,error); }
        };
    }]);

    //指令scope请参考http://www.linuxidc.com/Linux/2015-05/116924.htm
    app.directive('nprLink', function() {
        return {
            restrict: 'EA',
            require: ['^ngModel'], //要求必须有ng-model指令
            replace: true,
            scope: {//指令属性
                ngModel: '=', //指令中的与ng-model设置的对象相等
                player: '='   //把player属性值作为对象传递到指令的scope中
            },
            templateUrl: 'views/nprListItem.html',
            link: function(scope, ele, attr) {
                scope.duration = scope.ngModel.audio[0].duration.$text;
            }
        }
    });

    //控制器类
    app.controller('PlayerController', ['$scope','$http', 'player','nprService',function($scope,$http, player,nprService) {
        $scope.player = player;
        nprService.getPrograms(function(data, status) {
            console.log(data);
            $scope.programs = data.list.story;
        },function(data, status) {
            alert("加载失败!");
        });

    }]);

    //用于显示当前播放音乐信息
    app.controller('RelatedController', ['$scope', 'player',function($scope, player) {
            $scope.player = player;
            $scope.$watch('player.current', function(program) {
                if (program) {
                    $scope.related = [];
                    angular.forEach(program.relatedLink, function(link) {
                        $scope.related.push({
                            link: link.link[0].$text,
                            caption: link.caption.$text
                        });
                    });
                }
            });
        }]);

</script>
